package com.epoch.platform.common.controller;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.constant.Constant;
import com.epoch.platform.common.dao.SysAttachmentFiles;
import com.epoch.platform.common.service.CommonAttachService;
import com.epoch.platform.common.util.CommonAttachConstant;
import com.epoch.platform.common.util.CommonAttachUtils;
import com.epoch.platform.common.vo.AttachInfoDto;
import com.jfinal.upload.UploadFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/sys/common/attach")
public class CommonAttachController extends BaseController {
    private static final transient Logger LOG = LoggerFactory.getLogger(CommonAttachController.class);
    private CommonAttachService service = new CommonAttachService();;

    public void initFileList() {
        String businessId = this.getPara(CommonAttachConstant.PARAM_BUSINESSID);
        if (StringUtils.isNotEmpty(businessId)) {
            String businessType = this.getPara(CommonAttachConstant.PARAM_BUSINESSTYPE);
            List<SysAttachmentFiles> attachList = this.service.findByBusinessIdAndType(businessId, businessType);
            Map<String, Object> result = new HashMap<String, Object>();
            if (attachList != null) {
                int len = attachList.size();
                List<AttachInfoDto> attachInfoList = new ArrayList<AttachInfoDto>(len);
                for (int i = 0; i < len; i++) {
                    SysAttachmentFiles attach = attachList.get(i);
                    AttachInfoDto attachInfo = new AttachInfoDto(attach);
                    StringBuilder buff = new StringBuilder("/sys/common/attach/download");
                    buff.append(Constant.QMARK);
                    buff.append(CommonAttachConstant.PARAM_FILEKEY);
                    buff.append(Constant.EQUAL);
                    buff.append(attachInfo.getFileKey());
                    String downloadUri = buff.toString();
                    attachInfo.setDownloadUri(downloadUri);
                    LOG.debug("downloadUri: {}", downloadUri);
                    attachInfoList.add(attachInfo);
                }
                result.put(CommonAttachConstant.ATTACH_INFOS, attachInfoList);
            }
            this.renderJson(result);
        } else {
            this.renderError(400);
        }
    }

    public void upload() throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        UploadFile file = null;
        try {
            file = this.getFile();
        } catch (RuntimeException e) {
            LOG.error("get upload file failed", e);
            throw e;
        }
        if (file != null) {
            String fileName = file.getFileName();
            File dest = new File(CommonAttachUtils.getFileNameExt(fileName, true));
            fileName = dest.getName();
            FileUtils.copyFile(file.getFile(), dest);
            String fileKey = CommonAttachUtils.getFileKeyFromFileName(fileName);
            StringBuilder buff = new StringBuilder("/sys/common/attach/download");
            buff.append(Constant.QMARK);
            buff.append(CommonAttachConstant.PARAM_FILEKEY);
            buff.append(Constant.EQUAL);
            buff.append(fileKey);
            buff.append(Constant.AMP);
            buff.append(CommonAttachConstant.PARAM_NEWUP);
            buff.append(Constant.EQUAL);
            buff.append(Boolean.TRUE.toString());
            String downloadUri = buff.toString();
            result.put(CommonAttachConstant.PARAM_FILEKEY, fileKey);
            result.put(CommonAttachConstant.PARAM_DOWNLOADURI, downloadUri);
            LOG.debug("fileKey: {}", fileKey);
            LOG.debug("downloadUri: {}", downloadUri);
        }
        this.renderJson(result);
    }

    public void download() {
        String fileKey = this.getPara(CommonAttachConstant.PARAM_FILEKEY);
        if (StringUtils.isNotEmpty(fileKey)) {
            String newUpParam = this.getPara(CommonAttachConstant.PARAM_NEWUP);
            boolean newUp = Boolean.TRUE.toString().equals(newUpParam);
            String filePath = null;
            String fileName = null;
            if (newUp) {
                fileName = CommonAttachUtils.getFileNameFromFileKey(fileKey);
                filePath = CommonAttachUtils.obtainUploadFilePath(fileKey);
            } else {
                try {
                    SysAttachmentFiles attach = this.service.getByPk(fileKey);
                    fileName = attach.getStr(SysAttachmentFiles.FILE_ORIGINAL_NAME);
                    filePath = CommonAttachUtils.obtainAttachFilePath(attach);
                } catch (NumberFormatException e) {
                    LOG.error("invalid attachmentFileId '" + fileKey + "'", e);
                }
            }
            LOG.debug("filePath: {}", filePath);
            LOG.debug("download filename: {}", fileName);
            if (StringUtils.isNoneEmpty(filePath, fileName)) {
                this.renderFile(new File(filePath), fileName);
                return;
            }
        }
        this.renderError(404);
    }
}
